﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace AB.Common
{
    /// <summary>
    /// Dictionary对象帮助类
    /// </summary>
    public static class DictionaryHelper
    {
        /// <summary>
        /// Dictionary对象按照KEY的ASCII排序
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        public static Dictionary<TKey, TValue> Sort_ASCII<TKey, TValue>(this Dictionary<TKey, TValue> dic)
        {
            ArrayList arrayList = new ArrayList(dic.Keys);
            arrayList.Sort(StringComparer.Ordinal);
            Dictionary<TKey, TValue> sortedDictionary = new Dictionary<TKey, TValue>();
            foreach (TKey key in arrayList)
            {
                sortedDictionary.Add(key, dic[key]);
            }
            return sortedDictionary;
        }
        /// <summary>
        /// 将指定的键和值添加到字典中。已存在具有相同键的元素时覆盖
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="dic"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void AddCoverage<TKey, TValue>(this Dictionary<TKey, TValue> dic, TKey key, TValue value)
        {
            if (dic.ContainsKey(key))
            {
                dic[key] = value;
            }
            else
            {
                dic.Add(key, value);
            }
        }

    }
}
